package com.study.netty;


import com.study.receiver.Receiver;
import com.study.receiver.ReceiverFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * 处理连接与通讯
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {
    private final static Logger logger = LoggerFactory.getLogger(ServerHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = insocket.getAddress().getHostAddress();
        System.out.println("收到客户端[ip:" + clientIp + "]连接");
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 1.msg转为实际操作实体类  2.保存通道或者刷新通道  3.处理消息  4.写入ctx作为回复   5.写入异常则关闭通道；成功则保存通道
        Receiver receiver = ReceiverFactory.createReceiver(String.valueOf(msg));
        logger.info("解析到指令：" + msg.toString());
        if (receiver != null) {
            //解析数据，并把数据往后端传
            try {
                String command = msg.toString();
                String[] split = command.split(",");
                String imei = split[1];
                //判断，如果设备未入库，则直接通道断开
            /*    if(!InjectService.judgeIfInStorage(imei)){
                    ctx.channel().close();
                    return;
                }*/
                //保存或者刷新通道
                ChannelHandler.addOrRefreshChannel(imei, ctx.channel());
                receiver.parseMessage(String.valueOf(msg));
            } catch (Exception e) {
                logger.error("数据解析异常[{}]", e.getMessage());
            } finally {
                ReferenceCountUtil.release(msg);
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ChannelHandler.closeChannel(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("主动断开连接，通道关闭");
        ChannelHandler.closeChannel(ctx.channel());
    }

}